package jtmcraft.game.units.states;

import jtmcraft.game.units.CollisionManager;
import jtmcraft.game.units.GameUnit;
import jtmcraft.graphics.Sprite;

/**
 *
 * @author milosz
 */
public class MoveState extends MovableState  {

    private int x;    
    private int y;

    public MoveState(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public MoveState( GameUnit gameUnit) {
        this.x = gameUnit.getMidX();
        this.y = gameUnit.getMidY();
    }

    public void update(GameUnit gameUnit, long timestamp) {

        int dx = x - (gameUnit.getWidth() / 2) - gameUnit.getX();
        int dy = y - (gameUnit.getHeight() / 2) - gameUnit.getY();

        if (dx == 0 && dy == 0) {
            gameUnit.getSprite().setMove(false);
            return;
        }

        double dr = Math.sqrt(dx * dx + dy * dy);

        double i = dx / dr;
        double j = dy / dr;

        double sx = (i * .05 * timestamp);
        double sy = (j * .05 * timestamp);

        //to jes s
        if (Math.abs(sx) > Math.abs(dx)) {
            gameUnit.setX(gameUnit.getX() + (int) dx);
            gameUnit.setY(gameUnit.getY() + (int) dy);
            
            return;
        }

        int newX = gameUnit.getX() + (int) sx;
        int newY = gameUnit.getY() + (int) sy;

        // gameUnit.setX(newX);
        // gameUnit.setY(newY);

        double katRadian = Math.asin(j);

        Sprite sprite = gameUnit.getSprite();

        setMoveAction(sprite, katRadian, i);

        if( null == CollisionManager.getInstance().checkCollision( newX, newY, gameUnit ) ) {
            gameUnit.setX( newX );
            gameUnit.setY( newY );
        } else {
            for (int n = 45; n < 360; n += 45) {
                int prX = (int) (sx * Math.cos(Math.toRadians(n)) - sy * Math.sin(Math.toRadians(n)));
                int prY = (int) (sx * Math.sin(Math.toRadians(n)) + sy * Math.cos(Math.toRadians(n)));
                // remap to new position
                newX = prX + gameUnit.getX(); // slight speed up to avoid deadlock
                newY = prY + gameUnit.getY(); // slight speed up to avoid deadlock
                if (null == CollisionManager.getInstance().checkCollision(newX, newY, gameUnit)) {
                    gameUnit.setX(newX);
                    gameUnit.setY(newY);

                    dr = Math.sqrt(prX * prX + prY * prY);
                    i = prX / dr;
                    j = prY / dr;
                    katRadian = Math.asin(j);
                    setMoveAction(sprite, katRadian, i);

                    break;
                }
            }
        }
    }
}